/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package comunicacao;

import entities.Teatro;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import traffic.ControladorTrafego;

/**
 *
 * @author Leonardo Lino
 */
public class RmiClient {

    ReceiveMessageInterface rmiServer;
    Registry registry;
    String serverAddress = "23";
    String serverPort = "33";

    public RmiClient() {
        
        if (ControladorTrafego.server == ControladorTrafego.SERVER_APP){
            serverAddress = "10";
            serverPort = "2323";
        } else {
            serverAddress = "10";
            serverPort = "2323";
        }
    }
    
    

    public boolean connectList() {
        if (!connect()) {
            return false;
        }

        ArrayList<String> lista = null;
        try {
            lista = rmiServer.listTheaters();
        } catch (RemoteException ex) {
            Logger.getLogger(RmiClient.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        if (lista == null) {
            return false;
        }

        return true;
    }

    public boolean connectSelect() {
        
        //System.out.println("connectselect step 1");

        if (!connect()) {
            return false;
        }

        //System.out.println("connectselect step 2");
        
        Teatro teatro = null;

        try {
            teatro = rmiServer.getTheater(23);
        } catch (RemoteException ex) {
            Logger.getLogger(RmiClient.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
       // System.out.println("connectselect step 3");

        if (teatro == null) {
            return false;
        }

        return true;
    }

    public boolean connect() {
        try {
            // get the �gregistry�h
            registry = LocateRegistry.getRegistry(
                    serverAddress,
                    (new Integer(serverPort)).intValue());

            // look up the remote object
            rmiServer = (ReceiveMessageInterface) (registry.lookup("rmiServer"));
            return true;

            //rmiServer.getTheater(23);
        } catch (RemoteException e) {
            //e.printStackTrace();
            return false;
        } catch (NotBoundException e) {
           // e.printStackTrace();
            return false;
        }

    }

    public void setServerAddress(String serverAddress) {
        this.serverAddress = serverAddress;
    }

    public void setServerPort(String serverPort) {
        this.serverPort = serverPort;
    }
}
